#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <string>
#include <vector>

const std::string xmlPath = "haarcascade_frontalface_alt2.xml";

QImage  mat2QImage(cv::Mat cvImg)
{
    QImage qImg;
    if (cvImg.channels() == 3)                             //3 channels color image
    {

        cv::cvtColor(cvImg, cvImg, CV_BGR2RGB);
        qImg = QImage((const unsigned char*)(cvImg.data),
            cvImg.cols, cvImg.rows,
            cvImg.cols*cvImg.channels(),
            QImage::Format_RGB888);
    }
    else if (cvImg.channels() == 1)                    //grayscale image
    {
        qImg = QImage((const unsigned char*)(cvImg.data),
            cvImg.cols, cvImg.rows,
            cvImg.cols*cvImg.channels(),
            QImage::Format_Indexed8);
    }
    else
    {
        qImg = QImage((const unsigned char*)(cvImg.data),
            cvImg.cols, cvImg.rows,
            cvImg.cols*cvImg.channels(),
            QImage::Format_RGB888);
    }

    return qImg;

}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    m_timer(new QTimer),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(m_timer,&QTimer::timeout,this,&MainWindow::updateShow);
    connect(ui->pushButton_openCamer,&QPushButton::clicked,this,&MainWindow::openCamara);
    connect(ui->pushButton_closeCamer,&QPushButton::clicked,this,&MainWindow::closeCamer);
    connect(ui->pushButton_capture,&QPushButton::clicked,this,&MainWindow::capture);

    m_isClassifierLoaded = m_ccf.load(xmlPath);   //加载训练文件
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::updateShow()
{
    m_capture >> frame;
//    image = mat2QImage(frame);

//    ui->label_video->setPixmap(QPixmap::fromImage(image));

    imageShow(frame,ui->label_video);

    m_timer->start(50);
}

void MainWindow::imageShow(const Mat &img, QLabel *label)
{
    if(m_isClassifierLoaded)   //加载训练文件已成功
    {
        std::vector<Rect> faces;  //创建一个容器保存检测出来的脸
        Mat gray;

        cvtColor(img,gray,CV_BGR2GRAY); //转换成灰度图，因为harr特征从灰度图中提取

        equalizeHist(gray,gray);  //直方图均衡行

        m_ccf.detectMultiScale(gray,faces,1.1,2,0|CV_HAAR_SCALE_IMAGE, Size(30, 30)); //检测人脸

        //画方框
        for( int i = 0; i < faces.size(); i++ ){
            Point centera( faces[i].x, faces[i].y);
            Point centerb( faces[i].x + faces[i].width, faces[i].y + faces[i].height );
            rectangle(img,centera,centerb,Scalar(255,0,0));

        }
    }

    image = mat2QImage(img);
    image = image.mirrored(true, false);    //将图像水平镜像
    label->setPixmap(QPixmap::fromImage(image));
}


void MainWindow::openCamara()
{
    m_capture.open(0);

    m_timer->start(50);

}

void MainWindow::closeCamer()
{
    m_timer->stop();

    m_capture.release();
}

void MainWindow::capture()
{

}

